<template>
	<view class="container">
		<!-- <custom-header title="历史记录" show-back show-bg-color></custom-header> -->
		<view class="tabs">
			<view :class="['tab',{active:index==selectIndex}]" v-for="(item,index) in  tabList" :key="index"
				@click="handleSelect(index)">{{item}}</view>
		</view>
		<view class="layout">
			<view class='content-layout' v-if="list.length > 0">
				<view class="item" v-for="item in list" :key="item.id" @click="taskDetailFn(item)">
					<view class="title">{{ item.linkPath }}</view>
					<view class="bottom">
						<view v-if="item.status.code * 1 === 2" class="status success">解析成功</view>
						<view v-else-if="item.status.code * 1 === 3">
							<view v-if="item.type.code * 1 === 2" class="status error">解析失败</view>
							<view v-else class="status error">解析失败，点击重试</view>
						</view>
						<view v-else class="status loading">解析中</view>
						<view class="date">{{ item.extractTime }}</view>
					</view>
				</view>
			</view>
			<view class='content-layout no-data' v-else>
				暂无数据~
			</view>
		</view>
	</view>
</template>

<script setup>
	import { computed, ref, nextTick } from 'vue';
	import { onUnload, onLoad, onHide, onShow  } from '@dcloudio/uni-app';
	import { apiGetHistories, extractTextWithUrlVideo, extractVideoByUrl, checkId } from '@/utils/api.js';
	import { getStatusBarHeight, getTitleBarHeight } from '@/utils/system.js';
	
	const list = ref([]);

	const tabList = ref(['提取文字', '本地提取', '视频号提取', '短视频下载']);
	//激活颜色
	const activeColor = ref('#0051FE');

	//当前选中索引
	const selectIndex = ref(0);
	
	// 定时器
	const timerId = ref(null);

	//切换标签
	const handleSelect = (index) => {
		if (index !== selectIndex.value) {
			selectIndex.value = index;
			loadList();
		}
	}
	const loadList = async() => {
		const { success, data } = await apiGetHistories({type: selectIndex.value + 1});
		if (success) {
			list.value = data;
			if (uni.getStorageSync('tabInfo')) {
				uni.removeStorageSync('tabInfo')
			}
		}
	}
	const formatDate = (datetime) => {
		return datetime ? datetime.split(" ")[0] : "";
	}
	
	const taskDetailFn = (item) => {
		if (item.status.code === 2) {
			if (item.type.code === 1) {
				// 提取文字
				uni.navigateTo({
				  url: '/pages/extract_text/extract_text?pageFrom=history&type=text&taskId=' + item.id,
				})
			} else if (item.type.code === 4) {
				// 短视频下载
				uni.navigateTo({
				  url: '/pages/extract_text/extract_text?pageFrom=history&type=video&taskId=' + item.id,
				})
			} else if (item.type.code === 2) {
				// 本地提取
				uni.navigateTo({
				  url: '/pages/extract_local/extract_local?pageFrom=history&taskId=' + item.id,
				})
			}
		} else if (item.status.code === 3) {
			console.log(item);
			if (item.type.code === 2) {
				uni.showToast({
					title: '解析失败，请点击我的-联系客服',
					icon: 'none',
					duration: 2000,
				})
			} else {
				retryFn(item)
			}
			
		} else {
			uni.showToast({
				title: '正在解析，请稍后',
				icon: 'none',
				duration: 2000,
			})
		}
	}
	
	const retryFn = async (item) => {
		const userInfo = JSON.parse(uni.getStorageSync("userInfo"));
		const type = item.type.code;
		const userId = userInfo.id;
		const { data } = await checkId({
			userId,
			type
		}); 
		const params = {
			id: item.id,
			url: item.linkPath
		}
		if (data.valid) {
			//在有效期内
			if (type === 1) {
				onExtractText(params);
			} else if (type === 4) {
				onExtractVideo(params);
			}
		} else {
			uni.showModal({
				// title: data.message,
				content: '暂无可用时间，请联系客服购买兑换码',
				showCancel: false,
				success: function(res) {
					if (res.confirm) {
						// uni.navigateBack()
						uni.redirectTo({
						  url: '/pages/membership/membership'
						})
					}
				}
			})
		}
	}
	
	const onExtractText = async (params) => {
		const { success, data, message } = await extractTextWithUrlVideo(params); 
		if (success) {
			loadList();
		} else {
			uni.showToast({
				title: message,
				icon: 'none',
				duration: 5000,
			})
		}
	}
	
	const onExtractVideo = async (params) => {
		const { success, data, message } = await extractVideoByUrl(params); 
		if (success) {
			loadList();
		} else {
			uni.showToast({
				title: message,
				icon: 'none',
				duration: 5000,
			})
		}
	}
	
	const stopTimer = () => {
		clearInterval(timerId.value);
	}
	const startTimer = () => {
		stopTimer();		
		timerId.value = setInterval(() => {
			loadList();
		}, 5000);
	}
	
	onShow(() => {
		console.log('onShow');
		if (uni.getStorageSync('tabInfo')) {
			const tabInfo = uni.getStorageSync('tabInfo');
			selectIndex.value = tabInfo *1 - 1;
		} else {
			selectIndex.value = 0;
		}
		nextTick(() => {
		  loadList();
		  startTimer();
		})
	})
	
	onLoad(() => {
		console.log('onLoad');
	})
	onHide(() => {
		stopTimer();
	})
	
	onUnload(() => {
		stopTimer();
	})
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #F3F8FF;
		overflow: hidden;
		.tabs {
			width: 100%;
			display: flex;
			align-items: center;
			background-color: #fff;
			position: fixed;
			left: 0;
			top: 0;
			.tab {
				flex: 1;
				padding: 25rpx 10rpx;
				width: 0;
				box-sizing: border-box;
				text-align: center;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				color: #333;
				font-size: 28rpx;
				position: relative;
	
				&.active {
					// font-weight: bold;
					color: v-bind(activeColor);
					//下划线
					&::after {
						display: block;
						content: '';
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						width: 30px;
						height: 4rpx;
						background-color: v-bind(activeColor);
						border-radius: 6rpx;
					}
				}
			}
		}
		.layout {
			// padding: 28rpx 48rpx 48rpx 28rpx;
			display: flex;
			flex-direction: column;
			gap: 20rpx;
			height: 100vh;
			padding-top: 100rpx;
			overflow: hidden;
			
			.content-layout {
				height: 100vh;
				overflow: auto;
				padding: 0 32rpx 50rpx 32rpx;
				background-color: #fff;
				.item {
					background-color: white;
					border-radius: 8rpx;
					display: flex;
					flex-direction: column;
					padding: 20rpx 0;
					justify-content: space-between;
					border-bottom: 2rpx solid #f8f8f8;
					.title {
						font-size: 28rpx;
						color: #333333;
						font-weight: 500;
						overflow: hidden;
						-webkit-line-clamp: 2;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						margin-bottom: 32rpx;
					}
					.bottom {
						display: flex;
						align-items: center;
						justify-content: space-between;
						.status {
							font-size: 24rpx;
							font-weight: 400;
							border-radius: 8rpx;
							padding: 6rpx 20rpx;
							text-align: center;
						}
						.loading {
							color: #3374fe;
							background-color: #e6eeff;
							
						}
						.success {
							color: #01AA7A;
							background-color: #CCEEE4;
						}
						.error {
							color: #ED655E;
							background-color: #FBE0DF;
						}
						.date {
							font-size: 24rpx;
							font-weight: 400;
							color: #999999;
						}
					}
				}
				.item:last-child{
					border: none;
				}
			}
			
		    .no-data {
				text-align: center;
				padding-top: 200rpx;
				color: #999;
			}
		}
	}
</style>
